<template>
  <div class="map-page">
    <!-- 添加返回按钮 -->
    <div class="nav-header">
      <el-button 
        @click="goBack" 
        type="primary" 
        class="back-button"
      >
        <el-icon><ArrowLeft /></el-icon>
        返回上一页
      </el-button>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <div class="search-box">
        <el-input
          v-model="searchAddress"
          placeholder="搜索地址..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch" class="search-button">
          搜索
        </el-button>
      </div>
    </div>

    <!-- 地图容器 -->
    <div class="map-container" id="map-container"></div>
    
    <!-- 位置信息 -->
    <div id="location-info" class="location-info"></div>
  </div>
</template>

    <script>
import { Search, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

export default {
  name: 'MapView',
  components: {
    Search,
    ArrowLeft
  },
  setup() {
    const router = useRouter()

    // 返回上一页方法
    const goBack = () => {
      router.back()
    }

    return {
      goBack
    }
  },
  data() {
    return {
      map: null,
      geolocationControl: null,
      BMap: null,
      targetAddress: '',
      targetTitle: '',
      searchAddress: '', // 搜索地址
      currentMarker: null, // 当前标记点
      searchHistory: [], // 搜索历史
    }
  },
  mounted() {
    // 获取路由参数
    const { address, title, lat, lng } = this.$route.query;
    if (address) {
      this.targetAddress = address;
      this.targetTitle = title || '目标位置';
      this.searchAddress = address; // 将目标地址设置为初始搜索值
    }

    // 动态加载百度地图API
    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=EoZ84cprJs7YIjD8zcuJCJ04Sgc8C2Jt&callback=initBaiduMap&type=webgl`
    script.onerror = () => {
      ElMessage.error('地图加载失败，请检查网络连接')
    }
    document.head.appendChild(script)
    
    window.initBaiduMap = () => {
      this.BMap = window.BMapGL
      this.initMap()
    }
  },
  methods: {
    initMap() {
      try {
        this.map = new this.BMap.Map("map-container", {
          enableMapClick: false,
          displayOptions: {
            building: false
          }
        })
        
        this.map.setMapStyleV2({
          styleId: '4035af4c2c38c4b29e1ea273d31df5d5'
        })

        const point = new this.BMap.Point(116.404, 39.915)
        this.map.centerAndZoom(point, 15)
        
        // 添加控件
        this.map.addControl(new this.BMap.ScaleControl())
        this.map.addControl(new this.BMap.ZoomControl())
        this.map.addControl(new this.BMap.NavigationControl())
        this.map.enableScrollWheelZoom()

        // 如果有目标地址，则进行地址解析
        if (this.targetAddress) {
          this.searchLocation(this.targetAddress, this.targetTitle)
        } else {
          // 否则获取当前位置
          this.getCurrentLocation()
        }

        // 添加地图点击事件
        this.map.addEventListener('click', (e) => {
          this.handleMapClick(e)
        })
      } catch (error) {
        console.error('地图初始化失败:', error)
        ElMessage.error('地图初始化失败，请刷新页面重试')
      }
    },

    // 处理搜索
    handleSearch() {
      if (!this.searchAddress.trim()) {
        ElMessage.warning('请输入搜索地址')
        return
      }
      this.searchLocation(this.searchAddress)
    },

    // 修改搜索位置方法
    searchLocation(address, title = '搜索位置') {
      // 创建地址解析器实例
      const geoc = new this.BMap.Geocoder()
      
      // 创建本地搜索实例
      const localSearch = new this.BMap.LocalSearch(this.map, {
        renderOptions: {
          map: this.map,
          autoViewport: true,
          selectFirstResult: false
        },
        onSearchComplete: (results) => {
          if (results && results.getNumPois()) {
            const poi = results.getPoi(0)
            const point = poi.point
            
            // 清除之前的标记
            if (this.currentMarker) {
              this.map.removeOverlay(this.currentMarker)
            }
            
            // 清除本地搜索的结果标记
            this.map.clearOverlays()

            // 添加新标记
            this.currentMarker = new this.BMap.Marker(point)
            this.map.addOverlay(this.currentMarker)
            this.map.centerAndZoom(point, 17) // 调整缩放级别为17，显示更详细

            // 获取详细地址信息
            geoc.getLocation(point, (rs) => {
              const addComp = rs.addressComponents
              const fullAddress = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}${addComp.streetNumber}`
              
              // 创建信息窗口
              const infoWindow = new this.BMap.InfoWindow(`
                <div style="padding: 8px;">
                  <h4 style="margin: 0 0 5px 0;">${poi.title}</h4>
                  <p style="margin: 0;">详细地址：${fullAddress}</p>
                  <p style="margin: 5px 0 0;">经纬度：${point.lng}, ${point.lat}</p>
                </div>
              `)
              
              // 点击标记显示信息窗口
              this.currentMarker.addEventListener('click', () => {
                this.map.openInfoWindow(infoWindow, point)
              })
              
              // 自动打开信息窗口
              this.map.openInfoWindow(infoWindow, point)

              // 更新位置信息面板
              document.getElementById("location-info").innerHTML = `
                <div class="info-content">
                  <p><strong>${poi.title}</strong></p>
                  <p>详细地址：${fullAddress}</p>
                  <p>经纬度：${point.lng}, ${point.lat}</p>
                </div>
              `
            })
          } else {
            // 如果本地搜索失败，回退到地址解析
            this.geocoderSearch(address, title)
          }
        }
      })

      // 显示加载状态
      const loading = ElMessage({
        message: '正在搜索位置...',
        duration: 0,
        type: 'info'
      })

      // 设置搜索范围为北京市
      localSearch.setLocation('北京市')
      // 执行本地搜索
      localSearch.search(address)
      
      // 关闭加载状态
      loading.close()
    },

    // 添加地址解析方法作为备选
    geocoderSearch(address, title) {
      const geoc = new this.BMap.Geocoder()
      geoc.getPoint(address, (point) => {
        if (point) {
          if (this.currentMarker) {
            this.map.removeOverlay(this.currentMarker)
          }

          this.map.centerAndZoom(point, 17)
          this.currentMarker = new this.BMap.Marker(point)
          this.map.addOverlay(this.currentMarker)
          
          geoc.getLocation(point, (rs) => {
            const addComp = rs.addressComponents
            const fullAddress = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}${addComp.streetNumber}`
            
            const infoWindow = new this.BMap.InfoWindow(`
              <div style="padding: 8px;">
                <h4 style="margin: 0 0 5px 0;">${title}</h4>
                <p style="margin: 0;">详细地址：${fullAddress}</p>
                <p style="margin: 5px 0 0;">经纬度：${point.lng}, ${point.lat}</p>
              </div>
            `)
            
            this.currentMarker.addEventListener('click', () => {
              this.map.openInfoWindow(infoWindow, point)
            })
            
            this.map.openInfoWindow(infoWindow, point)

            document.getElementById("location-info").innerHTML = `
              <div class="info-content">
                <p><strong>${title}</strong></p>
                <p>详细地址：${fullAddress}</p>
                <p>经纬度：${point.lng}, ${point.lat}</p>
              </div>
            `
          })
        } else {
          ElMessage.error('未找到该地址，请尝试更详细的地址')
        }
      }, '北京市') // 指定检索范围为北京市
    },

    // 处理地图点击
    handleMapClick(e) {
      const geoc = new this.BMap.Geocoder()
      
      // 清除之前的标记
      if (this.currentMarker) {
        this.map.removeOverlay(this.currentMarker)
      }

      // 添加新标记
      const point = e.latlng
      this.currentMarker = new this.BMap.Marker(point)
      this.map.addOverlay(this.currentMarker)

      // 获取地址信息
      geoc.getLocation(point, (rs) => {
        const addComp = rs.addressComponents
        const address = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}${addComp.streetNumber}`
        
        const infoWindow = new this.BMap.InfoWindow(`
          <div style="padding: 8px;">
            <h4 style="margin: 0 0 5px 0;">选中位置</h4>
            <p style="margin: 0;">地址：${address}</p>
            <p style="margin: 5px 0 0;">经纬度：${point.lng}, ${point.lat}</p>
          </div>
        `)
        
        this.currentMarker.addEventListener('click', () => {
          this.map.openInfoWindow(infoWindow, point)
        })
        
        this.map.openInfoWindow(infoWindow, point)
      })
    },

    // 获取当前位置
    getCurrentLocation() {
      const geolocation = new this.BMap.Geolocation()
      geolocation.enableSDKLocation()
      
      geolocation.getCurrentPosition((r) => {
        if (geolocation.getStatus() == 0) {
          if (this.currentMarker) {
            this.map.removeOverlay(this.currentMarker)
          }

          this.currentMarker = new this.BMap.Marker(r.point)
          this.map.addOverlay(this.currentMarker)
          this.map.panTo(r.point)
          
          const geoc = new this.BMap.Geocoder()
          geoc.getLocation(r.point, (rs) => {
            const addComp = rs.addressComponents
            const address = `${addComp.province}${addComp.city}${addComp.district}${addComp.street}`
            
            document.getElementById("location-info").innerHTML = `
              <div class="info-content">
                <p><strong>当前位置</strong></p>
                <p>地址：${address}</p>
                <p>经纬度：${r.point.lng}, ${r.point.lat}</p>
              </div>
            `
          })
        } else {
          ElMessage.error('定位失败：' + geolocation.getStatus())
        }
      }, {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      })
    },

    // 添加到搜索历史
    addToSearchHistory(address) {
      if (!this.searchHistory.includes(address)) {
        this.searchHistory.unshift(address)
        if (this.searchHistory.length > 10) {
          this.searchHistory.pop()
        }
      }
    }
  }
}
    </script>

<style scoped>
.map-page {
  height: 100vh;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.nav-header {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.back-button:hover {
  transform: translateY(-2px);
  transition: all 0.3s ease;
}

.search-container {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  width: 400px;
}

.search-box {
  display: flex;
  gap: 10px;
  background: white;
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
}

.search-button {
  white-space: nowrap;
}

.map-container {
  flex: 1;
  width: 100%;
  height: 100%;
}

.location-info {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 90%;
  max-width: 500px;
  z-index: 1000;
}

.info-content {
  line-height: 1.6;
}

.info-content p {
  margin: 5px 0;
}

.info-content strong {
  color: #333;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-container {
    width: calc(100% - 40px);
    top: 80px; /* 在移动端将搜索框下移，避免与返回按钮重叠 */
  }
}
</style>